package com.shengdong.water.base

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.shengdong.water.R
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.lang.reflect.ParameterizedType

abstract class BaseVMFragment<VB : ViewDataBinding, VM : BaseViewModel> : Fragment() {

    protected lateinit var binding: VB
    protected lateinit var viewModel: VM
    private var isFirstLoad = true
    private var isVisibleToUser = false


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        initDataBinding(inflater, container)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 使用子类提供的方法创建ViewModel
        viewModel = createViewModel()
        initStatusBar()
        initViews()
        dataObserver()

        // 观察通用事件
        lifecycleScope.launch {
            viewModel.uiState.collect { state ->
                handleUIState(state)
            }
        }
    }

    // 初始化状态栏
    open fun initStatusBar() {}

    private fun handleUIState(state: UiState) {
        when (state) {
            is UiState.ShowLoading -> showLoading()
            is UiState.DismissLoading -> dismissLoading()
            is UiState.Error -> showError(state.message)
            else -> {}
        }
    }


    private fun initDataBinding(inflater: LayoutInflater, container: ViewGroup?) {
        binding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
        binding.lifecycleOwner = viewLifecycleOwner // 关键生命周期绑定// 绑定通用变量
    }

    override fun onResume() {
        super.onResume()
        if(isFirstLoad) {
            isFirstLoad = false
            initData()
        }
    }

    // 提供一个辅助方法，用于在子类中使用ViewModelProvider
    protected fun <T : BaseViewModel> viewModelProvider(modelClass: Class<T>): T {
        return ViewModelProvider(this)[modelClass]
    }
    protected open fun useImmersiveStatusBar(): Boolean = false

    // 状态栏是否是黑色字体
    protected open fun statusBarDarkMode(): Boolean = true

    // 状态栏颜色，默认透明
    protected open fun statusBarColor(): Int = Color.TRANSPARENT

    // 是否显示状态栏
    protected open fun showStatusBar(): Boolean = true
    abstract fun createViewModel(): VM
    abstract fun initViews()
    abstract fun initData()
    abstract fun dataObserver()

    abstract fun getLayoutId(): Int



    protected open fun showLoading() {
        // 实现加载对话框或委托给Activity
        (activity as? BaseVMActivity<*, *>)?.showLoading(loading = "加载中...")
    }

    protected open fun dismissLoading() {
        // 关闭加载对话框或委托给Activity
        (activity as? BaseVMActivity<*, *>)?.dismissLoading()
    }

    protected open fun showError(message: String) {
        // 显示错误信息或委托给Activity
        (activity as? BaseVMActivity<*, *>)?.showError(message)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (::binding.isInitialized) {
            binding.unbind()
        }
    }

}